package com.jeeplus.test.jlnu.graduationInfo.utils;

import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import org.apache.poi.ss.usermodel.*;

import java.util.*;

public class GrayStyleHandlerGraduation implements CellWriteHandler {

    private final Set<String> lockedFields; // 需要锁定的字段名集合
    private final Map<Workbook, CellStyle> lockedStyleCache = new HashMap<>();
    private final Map<Workbook, CellStyle> unlockedStyleCache = new HashMap<>();

    public GrayStyleHandlerGraduation(List<String> lockedFields) {
        this.lockedFields = new HashSet<>(lockedFields); // 接收锁定字段名列表
    }

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        // 跳过表头行
        if (context.getRowIndex() == 0) return;

        // 获取 Excel 表头名称（确保与 lockedFields 完全一致）
        String excelColumnName = context.getHeadData().getHeadNameList().get(0);

        // 判断是否需要锁定
        boolean isLocked = lockedFields.contains(excelColumnName);

        // 获取或创建样式
        Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
        CellStyle style = isLocked ?
                getOrCreateLockedStyle(workbook) :
                getOrCreateUnlockedStyle(workbook);

        // 应用样式到单元格
        context.getCell().setCellStyle(style);

        // 清除默认样式，防止覆盖
        WriteCellData<?> cellData = context.getFirstCellData();
        cellData.setWriteCellStyle(null);
    }

    // 锁定样式（红色背景 + 锁定）
    private CellStyle getOrCreateLockedStyle(Workbook workbook) {
        return lockedStyleCache.computeIfAbsent(workbook, key -> {
            CellStyle style = workbook.createCellStyle();
            style.setLocked(true);
            style.setFillForegroundColor(IndexedColors.RED.getIndex()); // 使用正确红色
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            setCommonBorders(style);
            return style;
        });
    }

    // 解锁样式（默认背景 + 解锁）
    private CellStyle getOrCreateUnlockedStyle(Workbook workbook) {
        return unlockedStyleCache.computeIfAbsent(workbook, key -> {
            CellStyle style = workbook.createCellStyle();
            style.setLocked(false); // 显式解锁
            return style;
        });
    }

    // 统一设置边框
    private void setCommonBorders(CellStyle style) {
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
    }

}
